import axios from 'axios';
import fs from 'fs';

const fileId = '7ryM2G71XRVwkQnkklWrbI';
const nodeId = '0:2671'; // 号码登录页面
const token = process.env.FIGMA_ACCESS_TOKEN;

console.log('🖼️ 获取Figma图片资源...');

try {
  // 1. 获取节点中的图片信息
  const nodeResponse = await axios.get(`https://api.figma.com/v1/files/${fileId}/nodes`, {
    headers: { 'X-Figma-Token': token },
    params: { ids: nodeId }
  });

  const nodeData = nodeResponse.data.nodes[nodeId];
  
  // 2. 查找所有图片节点
  const imageNodes = [];
  
  function findImageNodes(node, path = '') {
    if (node.type === 'RECTANGLE' && node.fills) {
      node.fills.forEach(fill => {
        if (fill.type === 'IMAGE') {
          imageNodes.push({
            id: node.id,
            name: node.name,
            path: path + '/' + node.name,
            imageRef: fill.imageRef
          });
        }
      });
    }
    
    if (node.children) {
      node.children.forEach(child => {
        findImageNodes(child, path + '/' + node.name);
      });
    }
  }

  if (nodeData && nodeData.document) {
    findImageNodes(nodeData.document);
  }

  console.log(`找到 ${imageNodes.length} 个图片节点:`);
  imageNodes.forEach((img, index) => {
    console.log(`${index + 1}. ${img.name} (ID: ${img.id})`);
  });

  // 3. 获取图片下载链接
  if (imageNodes.length > 0) {
    const imageIds = imageNodes.map(img => img.id).join(',');
    
    const imagesResponse = await axios.get(`https://api.figma.com/v1/images/${fileId}`, {
      headers: { 'X-Figma-Token': token },
      params: {
        ids: imageIds,
        format: 'png',
        scale: 2
      }
    });

    console.log('\n📥 图片下载链接:');
    const images = imagesResponse.data.images;
    
    for (const [nodeId, url] of Object.entries(images)) {
      const imageNode = imageNodes.find(img => img.id === nodeId);
      if (imageNode && url) {
        console.log(`${imageNode.name}: ${url}`);
        
        // 下载图片
        try {
          const imageResponse = await axios.get(url, { responseType: 'arraybuffer' });
          const fileName = `${imageNode.name.replace(/[^a-zA-Z0-9]/g, '_')}.png`;
          fs.writeFileSync(`../entry/src/main/resources/rawfile/${fileName}`, imageResponse.data);
          console.log(`✅ 已下载: ${fileName}`);
        } catch (downloadError) {
          console.log(`❌ 下载失败 ${imageNode.name}:`, downloadError.message);
        }
      }
    }
  } else {
    console.log('未找到图片资源，尝试获取所有可导出的元素...');
    
    // 获取页面中的所有可导出元素
    const exportResponse = await axios.get(`https://api.figma.com/v1/images/${fileId}`, {
      headers: { 'X-Figma-Token': token },
      params: {
        ids: nodeId,
        format: 'png',
        scale: 2
      }
    });

    if (exportResponse.data.images[nodeId]) {
      console.log('整个页面截图:', exportResponse.data.images[nodeId]);
    }
  }

} catch (error) {
  console.log('❌ 获取图片失败:', error.response?.status, error.response?.statusText);
  console.log('错误详情:', error.response?.data);
}
